/*
 * @Date: 2022-07-27 19:00:45
 * @LastEditors: wangjun haodreams@163.com
 * @LastEditTime: 2025-05-23 16:41:49
 * @FilePath: \libs\config\default.go
 * @Description:
 */
package config

import (
	"errors"
	"strings"
)

var globalConf Configer

// Save 全局的配置默认保存
func Save(paths ...any) (err error) {
	if save, ok := globalConf.(Saver); ok && save != nil {
		err = save.Save(paths...)
		return
	}
	err = errors.New("no support")
	return
}

// 设置某个key的值
func SetKeyValue(key, value string, desc ...string) {
	if set, ok := globalConf.(*Conf); ok && set != nil {
		descriptor := ""
		if len(desc) > 0 {
			descriptor = strings.Join(desc, "\n#")
		}
		val, ok := set.kv[key]
		if ok && val != nil {
			if descriptor != "" {
				val.Desc = descriptor
			}
			val.Value = value
			return
		}
		set.Set(key, value, descriptor)
	} else if set, ok := globalConf.(Setter); ok && set != nil {
		descriptor := ""
		if len(desc) > 0 {
			descriptor = strings.Join(desc, "\n#")
		}
		set.Set(key, value, descriptor)
	}
}

// 获取全局的配置
func GetSetting() Configer {
	return globalConf
}

// 设置全局的配置
func SetSetting(conf Configer) {
	globalConf = conf
}

func String(key string) string {
	return globalConf.String(key)
}

func Int(key string) (int, error) {
	return globalConf.Int(key)
}

func Int64(key string) (int64, error) {
	return globalConf.Int64(key)
}

func Bool(key string) (bool, error) {
	return globalConf.Bool(key)
}

func Float(key string) (float64, error) {
	return globalConf.Float(key)
}

func DefaultString(key string, defaultVal string) string {
	return globalConf.DefaultString(key, defaultVal)
}

func DefaultInt(key string, defaultVal int) int {
	return globalConf.DefaultInt(key, defaultVal)
}

func DefaultInt64(key string, defaultVal int64) int64 {
	return globalConf.DefaultInt64(key, defaultVal)
}

func DefaultBool(key string, defaultVal bool) bool {
	return globalConf.DefaultBool(key, defaultVal)
}

func DefaultFloat(key string, defaultVal float64) float64 {
	return globalConf.DefaultFloat(key, defaultVal)
}
